#!/bin/bash

# 修改APP_NAME为云效上的应用名
APP_NAME=0xcafe


PROG_NAME=$0
ACTION=$1
APP_START_TIMEOUT=20    # 等待应用启动的时间
APP_PORT=8088          # 应用端口
HEALTH_CHECK_URL=http://127.0.0.1:${APP_PORT}  # 应用健康检查URL
APP_HOME=/home/admin/${APP_NAME} # 从package.tgz中解压出来的jar包放到这个目录下
JAR_NAME=${APP_HOME}/app.jar # jar包的名字
JAVA_OUT=${APP_HOME}/logs/start.log  #应用的启动日志

export JAVA_HOME=/home/admin/jdk-24.0.2
export PATH=$JAVA_HOME/bin:$PATH

LOG_DIR=${APP_HOME}/logs

mkdir -p $LOG_DIR/{gc-log,heapdump}

initial_heap_size="2g"
max_heap_size="2g"

APP_RUN_PATH="--server.port=8088 --spring.data.redis.host=127.0.0.1 --spring.profiles.active=prod"

JVM_OPTS="-XX:+UseZGC \
	  -XX:+HeapDumpOnOutOfMemoryError \
	  -XX:HeapDumpPath=$LOG_DIR/heapdump/heapdump.hprof \
	  -XX:+UseNUMA \
	  -Xms${initial_heap_size} -Xmx${max_heap_size} \
	  -XX:MaxMetaspaceSize=256m \
	  -XX:NewRatio=4 \
	  -Xlog:gc*,gc+stats,safepoint:file=$LOG_DIR/gc-log/gc.log:time,uptimemillis,level,tags:filecount=10,filesize=20M"

# 创建出相关目录
mkdir -p ${APP_HOME}
mkdir -p ${APP_HOME}/logs
usage() {
    echo "Usage: $PROG_NAME {start|stop|restart}"
    exit 2
}

health_check() {
    exptime=0
    echo "checking ${HEALTH_CHECK_URL}"
    while true
        do
            status_code=`/usr/bin/curl -L -o /dev/null --connect-timeout 5 -s -w %{http_code}  ${HEALTH_CHECK_URL}`
            if [ "$?" != "0" ]; then
               echo -n -e "\rapplication not started"
            else
                echo "code is $status_code"
                if [ "$status_code" == "200" ];then
                    break
                fi
            fi
            sleep 1
            ((exptime++))

            echo -e "\rWait app to pass health check: $exptime..."

            if [ $exptime -gt ${APP_START_TIMEOUT} ]; then
                echo 'app start failed'
               exit 1
            fi
        done
    echo "check ${HEALTH_CHECK_URL} success"
}
start_application() {
    echo "starting java process"
    nohup java ${JVM_OPTS} -jar ${JAR_NAME} ${APP_RUN_PATH} > /dev/null 2> ${LOG_DIR}/nohup-error.log &
    echo $! > ${APP_HOME}/app.pid
    echo "started java process"
}

stop_application() {
   checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`
   
   if [[ ! $checkjavapid ]];then
      echo -e "\rno java process"
      return
   fi

   echo "stop java process"
   times=60
   for e in $(seq 60)
   do
        sleep 1
        COSTTIME=$(($times - $e ))
        checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`
        if [[ $checkjavapid ]];then
            kill -9 $checkjavapid
            echo -e  "\r        -- stopping java lasts `expr $COSTTIME` seconds."
        else
            echo -e "\rjava process has exited"
            break;
        fi
   done
   echo ""
}
start() {
    start_application
    health_check
}
stop() {
    stop_application
}
case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    *)
        usage
    ;;
esac
